<template>
	<div class="main">
		<div class="title">
			<span>活动管理&nbsp;/&nbsp;新增活动</span>
		</div>

		<el-form ref="activity" :model="activity" :rules="rules" label-width="120px" class="ruleForm" size="default"
			status-icon>
			<el-form-item label="活动名称" prop="activityName" required>
				<el-input v-model="activity.activityName" />
			</el-form-item>
			<el-form-item label="活动简介"> <el-input v-model="activity.information" type="textarea" />
			</el-form-item>
			<el-form-item label="信义分数" prop="score" required>
				<el-input v-model="activity.score" type="number" />
			</el-form-item>
			<el-form-item label="活动类型" prop="activityType" required>
				<el-select v-model="activity.activityType" placeholder="请选择活动类型">
					<el-option label="线上活动" value="线上活动" />
					<el-option label="线下活动" value="线下活动" />
				</el-select>
			</el-form-item>
			<el-form-item label="是否推荐">
				<el-switch v-model="activity.recommend" />
			</el-form-item>
			<el-form-item label="宣传图">
				<el-upload :action="uploadUrl" :data="uploadData" list-type="picture-card"
					:on-preview="handlePictureCardPreview" :on-remove="handleRemove" limit="1" :on-exceed="handleExceed"
					:on-error="handleError" :on-success="handleSuccess"  v-model:file-list="fileList">
					<el-icon>
						<Plus />
					</el-icon>
				</el-upload>
				<el-dialog v-model="dialogVisible">
					<img w-full :src="dialogImageUrl" alt="Preview Image" />
				</el-dialog>
			</el-form-item>
			<el-form-item style="margin-left: 200px;">
				<el-button type="primary" @click='submit("activity")'>确认</el-button>
				<el-button @click='cancel'>取消</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	import {
		mapActions,
		mapMutations
	} from 'vuex'

	import {
		FormInstance,
		FormRules,
		UploadFile,
		UploadProps,
		ElMessage
	} from 'element-plus'
	import {
		Delete,
		Download,
		Plus,
		ZoomIn
	} from '@element-plus/icons-vue'

	export default {
		//数据模型
		data() {
			return {
				activity: {
					id: '',
					activityName: '',
					information: '',
					activityType: '',
					recommend: false,
					score: 0,
					publicityMap: ''
				},
				dialogImageUrl: '',
				dialogVisible: false,
				uploadUrl: 'http://localhost:8830/comm_attachment/upload',
				uploadData: {
					'bizType': 'test_Type'
				},
				fileList: [], // 用于存储默认的文件列表

				//表单校验
				rules: {
					activityName: [{
							required: true,
							message: '请输入活动名称',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 8,
							message: '长度应在2到8个字符之间',
							trigger: 'blur'
						},
					],
					score: [{
							required: true,
							message: '请输入信义分数',
							trigger: 'blur'
						},
						{
							validator: (rule, value, callback) => {
								if (value < 0 || value > 100) {
									callback(new Error('信义分数应在0到100之间'));
								} else {
									callback();
								}
							},
							trigger: 'change'
						},
					],
					activityType: [{
						required: true,
						message: '请选择活动类型',
						trigger: 'blur'
					}],
				}
			}
		},

		//静态方法
		methods: {

			//映射
			...mapActions('activity', ['creatActivityStore', 'getDetailsByIdStore', 'setActivityId', 'getActivityId',
				'modifyActivityStore'
			]),

			/**
			 * 预览大图
			 */
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},

			handleExceed() {
				ElMessage({
					type: 'warning',
					message: '宣传图最多只可上传一张，请删除后再上传！',
				})
			},

			handleError(error) {
				console.log("====>error", error)
			},

			/**
			 * 图片上传处理
			 */
			handleSuccess(success) {
				if (success.successful) {
					this.activity.publicityMap = success.data
					ElMessage({
						type: 'success',
						message: '上传成功！',
					})
				} else {
					console.log("====>error", success)
				}
			},

			/**
			 * 提交
			 */
			async submit(formName) {
				this.$refs[formName].validate(async (valid) => {
					if (valid) {
						// 提交数据
						//如果有id则为修改，否则为新增
						if (this.activity.id) {
							const res = await this.modifyActivityStore({
								id: this.activity.id,
								activityName: this.activity.activityName,
								activityType: this.activity.activityType,
								activityInformation: this.activity.information,
								recommend: this.activity.recommend,
								publicityMap: this.activity.publicityMap,
								score: this.activity.score
							})
							if (res.successful) {
								this.$emit('activity-detail', 'Activity');
							} else {
								ElMessage({
									type: 'error',
									message: res.message,
								})
							}
						} else {
							const res = await this.creatActivityStore({
								activityName: this.activity.activityName,
								activityType: this.activity.activityType,
								activityInformation: this.activity.information,
								recommend: this.activity.recommend,
								publicityMap: this.activity.publicityMap,
								score: this.activity.score
							})
							if (res.successful) {
								this.$emit('activity-detail', 'Activity');
							} else {
								ElMessage({
									type: 'error',
									message: res.message,
								})
							}
						}
					} else {
						console.log('提交错误!!');
						return false;
					}
				})
			},

			/**
			 * 取消
			 */
			cancel() {
				this.$emit('activity-detail', 'Activity');
			}
		},

		/**
		 * 如果vueX中有activityId，则查询并回显至表单
		 */
		async beforeMount() {
			const activityId = await this.getActivityId()
			if (activityId) {
				this.activity.id = activityId
				const res = await this.getDetailsByIdStore(activityId)
				console.log('=====>Detail', res)
				if (res.successful) {
					this.activity.id = res.data.id
					this.activity.activityName = res.data.activityName
					this.activity.activityType = res.data.activityType
					this.activity.information = res.data.activityInformation
					this.activity.recommend = res.data.recommend == 'Y' ? true : false
					this.activity.score = res.data.score
					this.activity.publicityMap = res.data.publicityMap

					//如果 publicityMap 有值，则添加到 fileList
					if (this.activity.publicityMap) {
						this.fileList = [{
							url: 'http://localhost:8080/images/' + this.activity.publicityMap, // 这里假设 publicityMap 是图片的 URL
							name: '宣传图' // 可以自定义文件名
						}]
						console.log('===>image', this.fileList)
					}
				} else {
					ElMessage({
						type: 'error',
						message: res.message,
					})
				}
			}
		},

		beforeUnmount() {
			this.setActivityId(null)
		},

		//挂载组件
		components: {
			Delete,
			Download,
			Plus,
			ZoomIn
		},



	}
</script>

<style scoped>
	.main {
		width: 2000px;
		height: 1120px;
		margin-left: 600px;
		margin-top: 50px;
		display: flex;
		flex-direction: column;
	}

	.title {
		font-size: 14px;
		margin-bottom: 100px;
	}

	.ruleForm {
		width: 700px;
	}
</style>